package com.unis.service.znzf.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.unis.common.exception.app.AppRuntimeException;
import com.unis.common.exception.app.UploadFailureException;
import com.unis.common.secure.authc.UserInfo;
import com.unis.common.util.CreateImgUtil;
import com.unis.common.util.TimeUtil;
import com.unis.common.util.ValidateUtil;
import com.unis.dto.ResultDto;
import com.unis.mapper.znzf.ZnzfMapper;
import com.unis.model.system.DwDzz;
import com.unis.pojo.Attachment;
import com.unis.pojo.CxFlwsJtl;
import com.unis.pojo.ZfflwsJtl;
import com.unis.service.impl.BaseServiceImpl;
import com.unis.service.system.AttachmentService;
import com.unis.service.system.DwDzzService;
import com.unis.service.znzf.ZnzfService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;

/**
 * Created by Administrator on 2019/2/14/014.
 */
@Service("znzfService")
public class ZnzfServiceImpl extends BaseServiceImpl implements ZnzfService  {
    private static final Logger logger = LoggerFactory.getLogger(ZnzfServiceImpl.class);

    @Autowired
    private DwDzzService dwDzzService;
    @Autowired
    private AttachmentService attachmentService;
    @Autowired
    private ZnzfMapper znzfMapper;
    @Override
    public byte[] createFlws(String type, Map<String,String> map) throws Exception {
        byte[] b = null;
        if (map!=null && !map.isEmpty()){
            DwDzz dzz = null;
            UserInfo user = this.getUserInfo();
            try {
                dzz = dwDzzService.queryDwDzzByDwdm(user.getJgdm());
            } catch (Exception e) {
                logger.error("createFlws get DwDzz is error :"+e.getMessage());
                throw new UploadFailureException("createFlws get DwDzz is error :"+e.getMessage());
            }
            if (dzz!=null){
                if (StringUtils.isNotBlank(type) && StringUtils.equalsIgnoreCase(type,"cx")){
                    b = this.createCxFlws(map,dzz);
                }else if (StringUtils.isNotBlank(type) && StringUtils.equalsIgnoreCase(type,"zf")){
                    b = this.createZfFlws(map,dzz);
                }
            }else{
                logger.error("createFlws get DwDzz is error :此单位无调证字设置。");
                throw new UploadFailureException("createFlws get DwDzz is error :此单位无调证字设置。");
            }
        }else{
            logger.error("createFlws is error :map参数为空。");
            throw new UploadFailureException("createFlws is error :map参数为空。");
        }
        return b;
    }

    private byte[] createCxFlws(Map<String,String> map,DwDzz dzz) throws Exception{
        byte[] b = null;

        CxFlwsJtl cxws = new CxFlwsJtl();
        //设置账号相关
        cxws.setYhjg(map.get("bankname"));
        cxws.setShr(map.get("accountname"));
        cxws.setZh(map.get("cardnumber"));
        cxws.setZhlx(map.get("zhlx"));

        cxws.setDwmc(dzz.getDwmc());
        cxws.setDwjc(dzz.getDwjc());
        String nowYear = TimeUtil.getNow("yyyy");
        cxws.setDzz(dzz.getDzz()+"");

        if (!StringUtils.equalsIgnoreCase(nowYear,dzz.getDzyear())){
            dzz.setDzyear(nowYear);
            dzz.setDzz((long) 1);
            cxws.setDzz(dzz.getDzz()+"");
            try {
                dwDzzService.updateByPrimaryKey(dzz);
            } catch (Exception e) {
                throw new AppRuntimeException(e.getMessage());
            }
        }else{
            dzz.setDzz(dzz.getDzz()+1);
            try {
                dwDzzService.updateByPrimaryKey(dzz);
            } catch (Exception e) {
                throw new AppRuntimeException(e.getMessage());
            }
        }
        cxws.setDzyear(dzz.getDzyear());

        String[] mongo = dzz.getCxz().split("/");

        Attachment attachment = new Attachment();
        attachment.setAttachmentDb(mongo[0]);
        attachment.setCatalog(mongo[1]);
        attachment.setPk(mongo[2]);
        attachment = attachmentService.download(attachment);
        if (attachment!=null){
            cxws.setCxz(attachment.getContent());
        }
        String msg = ValidateUtil.valid(cxws);
        if (StringUtils.isNotBlank(msg)) {
            logger.error("valid createCxws CxFlwsJtl is error :" + msg);
            throw new UploadFailureException("valid createCxws CxFlwsJtl is error :" + msg);
        } else {
            try {
                b = CreateImgUtil.createCxFlwsImg(cxws);
            } catch (IOException e) {
                logger.error("createCxws generate img is error.\n" + e);
                throw new UploadFailureException("createCxws generate img is error.");
            }

        }
        return b;
    }

    private byte[] createZfFlws(Map<String,String> map,DwDzz dzz) throws Exception{
        byte[] b = null;

        ZfflwsJtl zfws = new ZfflwsJtl();
        //设置账号相关
        zfws.setYhjg(map.get("bankname"));
        //zfws.setShr(map.get("accountname"));
        zfws.setShr(map.get("shr"));
        zfws.setZh(map.get("cardnumber"));

        if(StringUtils.isBlank(map.get("zzfs"))){
            if( StringUtils.isNotBlank(map.get("zfCheckType")) && StringUtils.equalsIgnoreCase(map.get("zfCheckType"),"1")){
                zfws.setZzfs("网银");
            }else {
                zfws.setZzfs("账号");
            }
        }else {
            zfws.setZzfs(map.get("zzfs"));
        }
        zfws.setZzje(Double.parseDouble(map.get("zzje")));
        zfws.setZzsj(TimeUtil.strToDate(map.get("zzsj"),null));
        zfws.setAjlb(map.get("ajlb"));

        zfws.setDwmc(dzz.getDwmc());
        zfws.setDwjc(dzz.getDwmc());

        String[] mongo = dzz.getZfz().split("/");

        Attachment attachment = new Attachment();
        attachment.setAttachmentDb(mongo[0]);
        attachment.setCatalog(mongo[1]);
        attachment.setPk(mongo[2]);
        attachment = attachmentService.download(attachment);
        if (attachment!=null){
            zfws.setZfz(attachment.getContent());
        }
        String msg = ValidateUtil.valid(zfws);
        if (StringUtils.isNotBlank(msg)) {
            logger.error("valid createZfws ZfflwsJtl is error :" + msg);
            throw new UploadFailureException("valid createZfws ZfflwsJtl is error :" + msg);
        } else {
            try {
                b = CreateImgUtil.createZfFlwsImg(zfws);
            } catch (Exception e) {
                logger.error("createZfws generate img is error.\n" + e);
                throw new UploadFailureException("createZfws generate img is error.");
            }

        }
        return b;
    }
    @Override
    public String insertMongo(String type,String czType, Map<String,String> map) throws Exception {
        byte[] b = this.createFlws(czType, map);
        if (b!=null && b.length>0){
            Attachment attachment = new Attachment();
            attachment.setContent(b);
            attachment.setPk(new ObjectId().toString());
            attachment.setFilename(map.get("cardnumber")+"_"+ RandomStringUtils.randomAlphabetic(5)+".jpg");
            attachment.setContentType("image/jpeg");

            attachment.setAttachmentDb("flws_"+type+"_"+czType);
            try {
                attachment = attachmentService.upload(attachment);
                return attachment.getAttachmentDb()+"/"+attachment.getCatalog()+"/"+attachment.getPk();
            } catch (IOException e) {
                logger.error("znzfService upload to mongo is error.\n"+e);
                throw new UploadFailureException("znzfService upload to mongo is error.");
            }
        }
        return null;
    }

    @Override
    public ResultDto queryListByPage(String jjdpk, String cType, int pageNum, int pageSize) throws Exception {
        if (StringUtils.isNotBlank(jjdpk) && StringUtils.isNotBlank(cType)){
            PageHelper.startPage(pageNum,pageSize);

            PageInfo pageInfo = new PageInfo(znzfMapper.queryListByJjdpk(jjdpk, cType));

            ResultDto result = new ResultDto();
            result.setRows(pageInfo.getList());
            result.setPage(pageInfo.getPageNum());
            result.setTotal((int)pageInfo.getTotal());
            return result;
        }else {
            logger.error("ZnzfServiceImpl.queryListByPage时jjdpk、cType数据为空。");
            throw new AppRuntimeException("ZnzfServiceImpl.queryListByPage时jjdpk、cType数据为空。");
        }
    }
}
